package com.tripspins.app.services;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.preference.PreferenceManager;

import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.CurrentWeather;
import com.tripspins.app.bo.Pin;
import com.tripspins.app.bo.Route;
import com.tripspins.app.bo.Trip;
import com.tripspins.app.dao.PinDAO;
import com.tripspins.app.dao.TripDAO;
import com.tripspins.app.helper.ConstantsHelper;
import com.tripspins.app.helper.DbHelper;
import com.tripspins.app.helper.LocationHelper;
import com.tripspins.app.helper.WeatherHelper;
import com.tripspins.app.interfaces.OnTaskCompleted;
import com.google.android.gms.maps.model.LatLng;

import java.util.Date;

/**
 * Created by João.Rutkoski on 16/10/13.
 */
public class BackgroundPinGeneratorService extends Service implements OnTaskCompleted {

    WeatherHelper weatherHelper;
    CurrentWeather currentWeather;
    SharedPreferences settings;
    IBinder mBinder;
    LocationHelper locationHelper;
    DbHelper dbHelper;
    SQLiteDatabase database ;
    TripDAO tripDAO;
    Trip currentTrip;
    LatLng position;


    public BackgroundPinGeneratorService ()
    {

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        weatherHelper = new WeatherHelper(this);
        locationHelper = LocationHelper.getInstance(getApplicationContext());

        dbHelper = new DbHelper(getApplicationContext());
        database = dbHelper.getReadableDatabase();
        tripDAO = new TripDAO(database);
        currentTrip =tripDAO.getTrip();
        database.close();


        if(currentTrip != null && settings.getBoolean(ConstantsHelper.PREFERENCES_BOOL_AUTO_PIN,false)){


            //TODO: Listen camera
            //TODO: Listen music player

            new Thread(new Runnable() {
                public void run() {
                    while (true){
                        LatLng newPosition = locationHelper.getPosition();
                        if(position != newPosition)
                        {
                            position = newPosition;
                            if(locationHelper.distance(position, newPosition) >= Integer.parseInt(settings.getString("pref_key_int_distance", "100"))) {
                                position = newPosition;

                                if(currentTrip != null && position != null) {

                                    if(settings.getBoolean("pref_key_bool_weather",false))
                                        weatherHelper.getWeather(position);
                                    else
                                        createAutoPin();
                                }
                            }
                        }
                        try{
                            Thread.sleep(Integer.parseInt(settings.getString("pref_key_int_interval", "10")) * 1000 * 60);
                        }
                        catch(Exception e){
                            stopSelf();
                        };
                    }
                }
            }).start();
        }
        return super.onStartCommand(intent, flags, startId);


    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTaskCompleted(Route r) {

    }

    @Override
    public void onTaskCompleted(CurrentWeather w) {
        createAutoPin(w);
    }

    private void createAutoPin(CurrentWeather w) {
        DbHelper dbHelper = new DbHelper(getApplicationContext());
        try {
            SQLiteDatabase database = dbHelper.getReadableDatabase();
            TripDAO tripDAO = new TripDAO(database);
            Trip currentTrip = tripDAO.getTrip();
            database.close();
            Pin pin = new Pin();
            pin.setDate(new Date());
            pin.setLatLng(locationHelper.getPosition());
            pin.setCurrentWeather(w);
            pin.setAddress(locationHelper.getAddress());
            pin.setTitle(settings.getString("pref_key_txt_title", ""));
            pin.setTripId(currentTrip.getId());
            database = dbHelper.getWritableDatabase();
            PinDAO pinDao = new PinDAO(database);
            pin.setId(pinDao.persist(currentTrip.getId(), pin));
            database.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }


    }
    private void createAutoPin() {
        DbHelper dbHelper = new DbHelper(getApplicationContext());
        try {
            SQLiteDatabase database = dbHelper.getReadableDatabase();
            Pin pin = new Pin();
            pin.setDate(new Date());
            pin.setLatLng(locationHelper.getPosition());
            pin.setAddress(locationHelper.getAddress());
            pin.setTitle(settings.getString("pref_key_txt_title", ""));
            pin.setTripId(currentTrip.getId());
            database = dbHelper.getWritableDatabase();
            PinDAO pinDao = new PinDAO(database);
            pin.setId(pinDao.persist(currentTrip.getId(), pin));
            database.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }


    }
    @Override
    public void onTaskCompleted(Bitmap b) {

    }

    @Override
    public void onTaskCompleted(Attachment att) {

    }
}
